﻿using System;
using System.IO;
using System.Xml.Serialization;
using Mrsoft.Common;


namespace Mrsoft.Core {
    /// <summary>
    /// 用于自动存取XML文件
    /// </summary>
    public static class XmlSaver<T> {
        public static bool Save(string fileName, T obj) {
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
            fileName = fileName.Replace("\\", "/");
            var conf = new Config<string>("Serializable", fileName, "");
            conf.Value = json;
            return true;
        }

        public static bool FromXml(string fileName, out T obj, params Type[] extra) {

            obj = default(T);
            fileName = fileName.Replace("\\", "/");
            var conf = new Config<string>("Serializable", fileName, "");
            if (File.Exists(fileName)) {
                FileStream fs = null;
                try {
                    var w = new XmlSerializer(typeof(T), extra);
                    fs = File.OpenRead(fileName);
                    obj = (T)w.Deserialize(fs);
                    fs.Close();
                    conf.Value = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
                    File.Delete(fileName);
                    return true;
                }
                catch {
                    if (fs != null)
                        fs.Close();
                    return false;
                }
            }
            else {
                if (!string.IsNullOrWhiteSpace(conf.Value)) {
                    obj = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(conf.Value);
                    return true;
                }
                return false;
            }
        }

    }
}
